
import time
import copy

from dexen.user.libs import constants as dc, server_api

from libs import input_reading, constants


""" GLOBALS """
pop_api = server_api.PopAPIFactory()
boxes = input_reading.read_input()
n_boxes = len(boxes)

INF = 1000000000

best_individual = {
    constants.AREA : INF
}
file_id = 0
iter = 0


def is_best(individual):
    global best_individual    
    if (individual[constants.AREA] < best_individual[constants.AREA]):
        best_individual = copy.deepcopy(individual)

def evaluate_individual_width(individual):
    phenotype = individual[constants.PHENOTYPE]
    genotype = individual[constants.GENOTYPE] 
    
    orient = genotype["orient"]
    
    max_found = 0
    side = 0
    for i in range(n_boxes):
        if orient[i] == 0:
            side = boxes[i]['w']
        else:
            side = boxes[i]['h']
        if phenotype[i]['x'] + side > max_found:
            max_found = phenotype[i]['x'] + side
    individual[constants.WIDTH] = float(max_found)
    
def evaluate_width(population):
    for individual in population:
        evaluate_individual_width(individual)

def evaluate_individual_height(individual):
    phenotype = individual[constants.PHENOTYPE]
    genotype = individual[constants.GENOTYPE] 
    
    orient = genotype["orient"]

    max_found = 0
    side = 0
    for i in range(n_boxes):
        if orient[i] == 0:
            side = boxes[i]['h']
        else:
            side = boxes[i]['w']
        if phenotype[i]['y'] + side > max_found:
            max_found = phenotype[i]['y'] + side
    individual[constants.HEIGHT] = float(max_found)
                
def evaluate_height(individuals):
    for individual in individuals:
        evaluate_individual_height(individual)

def evaluate(individuals):
    global file_id, iter, cur_time
    
    """ WE ONLY NEED THE ORIENT UNDER GENOTYPE !!! """
    """
    individuals = pop_api.downloadLiveIndividuals(
        select = (constants.PHENOTYPE, constants.GENOTYPE), 
        where = (
            (constants.PHENOTYPE, dc.NOT_EQUAL, None),
            (constants.HEIGHT, dc.EQUAL, None),
            (constants.WIDTH, dc.EQUAL, None)            
        ), 
        count = pop_api.getGlobalData()[constants.EVALUATION]
    )  
    """
    
    iter += 1
    file_id += 1
    print "I am in evaluation", iter
    
    evaluate_width(individuals)
    evaluate_height(individuals)
    for individual in individuals:
        individual[constants.AREA] = individual[constants.WIDTH] * individual[constants.HEIGHT]
        is_best(individual)
    
    if iter % 10 == 0: print "At iter:", iter, "The best individual: ", best_individual
    
    #pop_api.uploadIndividuals(individuals)
    return individuals
    